const webpack = require('webpack');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
// 去除console
const UglifyJsPlugin = require('terser-webpack-plugin');
const FileManagerPlugin = require('filemanager-webpack-plugin');
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const path = require('path');
const mock = require('./mock');
const resolve = (dir) => path.join(__dirname, dir); // 路径

const IS_PROD = ['production', 'prod', 'test'].includes(process.env.NODE_ENV);
const IS_DEV = ['development'].includes(process.env.NODE_ENV);
console.log(process.env.NODE_ENV);

module.exports = {
  // lintOnSave: false, //关闭eslint检查
  // publicPath: isDev ? '' : querystring.unescape('<%=request.getContextPath()%>'),
  publicPath: process.env.BASE_URL,
  outputDir: 'ds-mobile',
  productionSourceMap: false,
  css: {
    requireModuleExtension: true, // 是否开启CSSmodule并保留xxx.module.css后缀
    loaderOptions: {
      postcss: {
        plugins: [
          require('postcss-pxtorem')({
            // 以设计稿750为例， 750 / 10 = 75
            rootValue: 75,
            propList: ['*'],
            selectorBlackList: ['van'],
          }),
        ],
      },
      less: {
        javascriptEnabled: true,
      },
      sass: {
        additionalData: `
        @use 'sass:math';
        @import "@/styles/global.scss";`,
      },
    },
  },
  chainWebpack: (config) => {
    // 移除 preload 插件
    config.plugins.delete('preload');
    // 移除 prefetch 插件
    config.plugins.delete('prefetch');
    config
      .plugin('ignore')
      .use(new webpack.ContextReplacementPlugin(/moment[/\\]locale$/, /zh-cn$/));
    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(!IS_PROD, (config) => config.devtool('cheap-source-map'));

    // 配置相关loader，支持修改，添加和替换相关的loader
    config.resolve.alias.set('@', resolve('src'));
    // 打包分析
    if (IS_PROD) {
      config.optimization.delete('splitChunks');
      // config.plugin('webpack-report').use(BundleAnalyzerPlugin, [
      //   {
      //     analyzerMode: 'static'
      //   }
      // ])
    }
    config.plugin('html').tap((args) => {
      args[0].title = '得实移动端啊';
      return args;
    });

    // svg rule loader
    config.module.rule('svg').exclude.add(resolve('src/assets/icons')).end();

    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      });
  },
  configureWebpack: (config) => {
    if (IS_PROD) {
      config.plugins.push(
        new UglifyJsPlugin({
          terserOptions: {
            warnings: false,
            compress: {
              drop_debugger: true, // 注释console
              drop_console: true,
              pure_funcs: ['console.log'], // 移除console
            },
          },
          extractComments: false, // 是否将注释提取到一个单独的文件中
          sourceMap: false,
          parallel: true,
        }),
        new FileManagerPlugin({
          events: {
            onEnd: {
              delete: ['.ds-mobile.zip'],
              archive: [
                {
                  source: '.ds-mobile',
                  destination: '.ds-mobile.zip',
                },
              ],
            },
          },
        })
        // new CompressionPlugin({
        //     /* [file]被替换为原始资产文件名。
        //        [path]替换为原始资产的路径。
        //        [dir]替换为原始资产的目录。
        //        [name]被替换为原始资产的文件名。
        //        [ext]替换为原始资产的扩展名。
        //        [query]被查询替换。*/
        //     filename: '[path].gz[query]',
        //     //压缩算法
        //     algorithm: 'gzip',
        //     //匹配文件
        //     test: /\.js$|\.css$|\.html$/,
        //     //压缩超过此大小的文件,以字节为单位
        //     threshold: 10240,
        //     minRatio: 0.8,
        //     //删除原始文件只保留压缩后的文件
        //     deleteOriginalAssets: true
        // })
      );
      config.optimization = {
        splitChunks: {
          cacheGroups: {
            common: {
              name: 'chunk-common',
              chunks: 'initial',
              minChunks: 2,
              maxInitialRequests: 5,
              minSize: 0,
              priority: 1,
              reuseExistingChunk: true,
              enforce: true,
            },
            vendors: {
              name: 'chunk-vendors',
              test: /[\\/]node_modules[\\/]/,
              chunks: 'initial',
              priority: 2,
              reuseExistingChunk: true,
              enforce: true,
            },
            vant: {
              name: 'chunk-vant',
              test: /[\\/]node_modules[\\/]vant[\\/]/,
              chunks: 'all',
              priority: 3,
              reuseExistingChunk: true,
              enforce: true,
            },
          },
        },
      };
    }
  },
  devServer: {
    port: 3010,
    stats: 'errors-only',
    proxy: {
      '/ds': {
        /**
         * API 使用本地Mock（Mock目录在根目录/mock/*）
         * @param req {Request}   | 收到请求
         * @param res {Response}  | 发送回复
         * @param proxyOptions    | 代理选项，本地纯mock场景不使用
         */
        target: 'http://localhost:3010',
        bypass: function (req, res, proxyOptions) {
          let { pathname } = new URL(req.url, 'http://' + req.headers.host);
          // 取出请求中路径部分，并标准化，用于匹配mock映射
          pathname = pathname.replace(/\/+$/, '').toLowerCase();

          // 取出mock映射对应的数据
          const mockFunc = mock[pathname];

          // 数据存在则返回
          if (mockFunc) {
            return res.json(mockFunc(req));
          }

          // 否则使用404兜底
          res.status = 404;
          return res.json({ message: `api "${pathname}" is not exists.` });
        },
      },
    },
  },
};
